package handle

import (
	"fmt"
	"os"

	"protocx/entity"

	"github.com/gofiber/fiber/v2"
)

func NewReq() Req {
	return Req{}
}

type Req struct {
}

func (r Req) InitRoute(server *fiber.App) {
	p := server.Group("/req")
	p.Post("/form-data", r.form())
	p.Post("/form-ulencoded", r.formUrlencoded())

	p.Get("/path/:name/:ext", r.path())
	p.Get("/query", r.query())
	p.Post("/binary", r.binary())
	p.Post("/json", r.json())
	p.Post("/raw", r.raw())
}
func (r Req) form() fiber.Handler {
	return func(ctx *fiber.Ctx) error {
		form, err := ctx.MultipartForm()
		if err != nil {
			return ctx.JSON(err)
		}
		for s, strings := range form.Value {
			fmt.Println("MultipartForm.Value", s, strings)
		}
		for s, headers := range form.File {
			fmt.Println("MultipartForm.File", s, headers)
		}
		return nil
	}
}

// ??
func (r Req) formUrlencoded() fiber.Handler {
	return func(ctx *fiber.Ctx) error {
		form, err := ctx.MultipartForm()
		if err != nil {
			return ctx.JSON(err)
		}
		for s, strings := range form.Value {
			fmt.Println("MultipartForm.Value", s, strings)
		}
		for s, headers := range form.File {
			fmt.Println("MultipartForm.File", s, headers)
		}
		return nil
	}
}
func (r Req) query() fiber.Handler {
	return func(ctx *fiber.Ctx) error {
		fmt.Println("Queries", ctx.Queries())
		var person entity.Person
		if err := ctx.QueryParser(&person); err != nil {
			return ctx.JSON(err)
		}
		return ctx.JSON(person)
	}
}
func (r Req) path() fiber.Handler {
	return func(ctx *fiber.Ctx) error {
		fmt.Println("path", ctx.AllParams())
		person := entity.Person{}
		return ctx.ParamsParser(&person)
	}
}

func (r Req) binary() fiber.Handler {
	return func(ctx *fiber.Ctx) error {
		body := ctx.Body()
		return os.WriteFile("./upload.png", body, 0644)
	}
}
func (r Req) json() fiber.Handler {
	return func(ctx *fiber.Ctx) error {
		person := entity.Person{}
		err := ctx.BodyParser(&person)
		if err != nil {
			return err
		}
		return ctx.JSON(person)
	}
}
func (r Req) raw() fiber.Handler {
	return func(ctx *fiber.Ctx) error {
		_, err := ctx.WriteString(ctx.String())
		if err != nil {
			return err
		}
		return nil
	}
}
